package wqh.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import wqh.domain.DtDevice;
import wqh.pojo.IPConver;
import wqh.pojo.MapRet;
import wqh.pojo.Select2DeviceName;
import wqh.service.DtDeviceService;
import wqh.service.DtMapPosGeoService;
import wqh.service.DtMapPosService;
import wqh.service.DtSensorService;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by devts on 2016/11/30.
 */
@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/water/dt_device")
public class DtDeviceJSONController {

    @Autowired
    private DtDeviceService dtDeviceService;

    @Autowired
    private DtSensorService dtSensorService;

    @Autowired
    private DtMapPosService dtMapPosService;

    @RequestMapping(value = "/getAll", method = RequestMethod.GET)
    public Object getAll()
    {
        List<DtDevice> dtDevices = dtDeviceService.findAll();
        return MapRet.DATA(dtDevices);
    }

    @RequestMapping(value = "/getAll2", method = RequestMethod.GET)
    public Object getAll2()
    {
        List<DtDevice> dtDevices = dtDeviceService.findAll();
        List<Object> objList = new ArrayList<Object>();
        if(dtDevices.size() == 0) return MapRet.DATA(null);
        for(DtDevice d : dtDevices){
            Map<String,Object> map = new HashMap<String, Object>();
            map.put("id",d.getId());
            map.put("text",d.getName());
            objList.add(map);
        }
        return MapRet.DATA(objList);
    }


    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public Object add(@RequestBody DtDevice dtDevice)
    {
        try {
            dtDevice.setId(null);
            if(!IPConver.isValidIp(dtDevice.getIp())) return MapRet.IP_ERROR();
            dtDeviceService.insert(dtDevice);
            return MapRet.SQL_SUCCESS();
        }catch (Exception e){
            e.printStackTrace();
            return MapRet.SQL_ERROR();
        }
    }
    @RequestMapping(value = "/getSelect2DeviceName",method = RequestMethod.GET)
    public Object getSelect2DeviceName()
    {
        List<DtDevice> dtDeviceList = dtDeviceService.findAll();
        List<Select2DeviceName> select2DeviceNameList = new ArrayList<Select2DeviceName>();
        for(DtDevice dtDevice : dtDeviceList)
        {
            Select2DeviceName s = new Select2DeviceName(dtDevice.getId(),dtDevice.getName());
            select2DeviceNameList.add(s);
        }
        return select2DeviceNameList;
    }
    @RequestMapping(value = "/update",method = RequestMethod.POST)
    public Object update(HttpServletRequest httpServletRequest,
                          @RequestParam(value = "id",required = true) Integer id,
                          @RequestParam(value = "name",required = true) String name,
                          @RequestParam(value = "ip",required = true) String ip,
                          @RequestParam(value = "detail",required = false,defaultValue = "0") String detail,
                          @RequestParam(value = "file",required = false,defaultValue = "null")MultipartFile file)
    {
       try{
           DtDevice dtDevice = dtDeviceService.findAllById(id);
           if(dtDevice == null) return MapRet.SQL_ERROR("系统中无此记录");
           if(!IPConver.isValidIp(ip)) return MapRet.IP_ERROR();
           if(file != null && !file.isEmpty())
           {
               removePicture(dtDevice,httpServletRequest);
               String localPath = "upload\\picture\\";
               String uploadPath = httpServletRequest.getServletContext().getRealPath("/") + localPath;
               File uploadDir = new File(uploadPath);
               if(!uploadDir.exists())
               {
                   uploadDir.mkdirs();
               }
               String fileName = file.getOriginalFilename();
               if(fileName != null)
               {
                   byte[] bytes = file.getBytes();
                   fileName = System.currentTimeMillis() + fileName;
                   File serverFile = new File(uploadDir.getAbsolutePath() + File.separator + fileName);
                   BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));
                   stream.write(bytes);
                   stream.close();
                   dtDevice.setPicture(localPath + serverFile.getName());
               }
           }
           dtDevice.setId(id);
           dtDevice.setName(name);
           dtDevice.setIp(ip);
           dtDevice.setDetail(detail);
           dtDeviceService.updateById(dtDevice);
           return MapRet.SUCCESS();
       }catch (Exception e){
           e.printStackTrace();
           return MapRet.ERROR();
       }
    }

    @RequestMapping(value = "/delete",method = RequestMethod.POST)
    public Object delete(HttpServletRequest httpServletRequest,
                         @RequestParam(value = "id",required = true) int id)
    {
        try {
            DtDevice dtDevice = dtDeviceService.findAllById(id);
            if(dtDevice == null) return MapRet.SQL_ERROR("系统中无此记录");
            removePicture(dtDevice,httpServletRequest);
            dtDeviceService.deleteById(id);
            dtSensorService.deleteByDeviceId(id);
            dtMapPosService.deleteByDeviceId(id);
            return MapRet.SUCCESS();
        }catch (Exception e){
            e.printStackTrace();
            return MapRet.ERROR();
        }
    }

    public void removePicture(DtDevice device,HttpServletRequest httpServletRequest)
    {
        String localPath = "upload\\picture\\";
        String uploadPath = httpServletRequest.getServletContext().getRealPath("/") + localPath;
        if(device.getPicture() != null && device.getPicture().length() != 0 && !device.getPicture().equals("0"))
        {
            String serverPath = uploadPath +device.getPicture();
            File serverFile = new File(serverPath);
            if(serverFile.isFile() && serverFile.exists())
            {
                serverFile.delete();
            }
        }
    }

}
